package com.ndp.fb.walle.websocket;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.exception.ResourceNotificationMsgManager;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.redis.model.UserProfile;
import com.ndp.fb.walle.business.MessageService;
import com.ndp.fb.walle.model.vo.eventnotificationmessage.EventNotificationMessageVo;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;


/**
 * Created by hermen on 7/22/2015.
 */
@Component
public class WebsocketClient extends TextWebSocketHandler {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    private static final List<WebSocketSession> sessions;

    static {
        sessions = new ArrayList<>();
    }

    @Autowired
    private MessageService messageService;

    @Autowired
    private RedisClient redisClient;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        if (message.getPayload().toString().equals("test")) {
            //心跳测试
            logger.info("成功接收到从websocket客户端发来的消息，连接一切正常！");
            Map m = new HashMap();
            m.put("message", "websocket is ok!");
            m.put("flag", "test");
            session.sendMessage(new TextMessage(JSON.toJSONString(m)));
        } else if (message.getPayload().toString().contains("userId:")) {
            UserProfile p = (UserProfile) redisClient.get(message.getPayload().toString().substring(7));
            session.getAttributes().put("userId", p.getUser().getTicket());
            session.getAttributes().put("language",p.getUser().getLanguage());
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
        logger.info("websocket add session: " + session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
        logger.info("websocket remove session: " + session.getId());
    }


    public void sendMessageToOne(String userId, Pager<EventNotificationMessageVo> pager) throws IOException {
        Iterator<WebSocketSession> iterator = sessions.iterator();
        logger.info("sessions 数量为:" + sessions.size());
        while (iterator.hasNext()) {
            WebSocketSession webSocketSession = iterator.next();
            try {
                if (webSocketSession.isOpen()) {
                    if (webSocketSession.getAttributes().get("userId").toString().equals(userId)) {

                        String language = (String)webSocketSession.getAttributes().get("language");
                        for (EventNotificationMessageVo eventNotificationMessageVo : pager.getResultList()) {
                            String eventKey = eventNotificationMessageVo.getEventKey();
                            String eventValues = eventNotificationMessageVo.getEventValues();
                            String body = ResourceNotificationMsgManager.getNotificationResource(language,eventKey,eventValues);
                            eventNotificationMessageVo.setBody(body);

                            if (ResourceNotificationMsgManager.isCN(language)) {
                                eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getName());
                            } else {
                                eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getEnName());
                            }
                        }
                        String s = JSON.toJSONString(pager);
                        webSocketSession.sendMessage(new TextMessage(s));
                        logger.info("消息已发送给用户" + userId+">>>>>>>>>>>>>>"+s);
                    }
                } else {
                    sessions.remove(webSocketSession);
                }
            } catch (Exception e) {
                sessions.remove(webSocketSession);
                logger.error("推送失败>>>", e);
            }
        }
    }
}
